package com.atguigui.leetcode;

import java.util.HashMap;
import java.util.Map;

/**
 * Project: leetcode
 * Package: com.atguigui.leetcode
 * Version: 1.0
 * <p>
 * Created by WJX on 2022/10/17 9:00
 */
public class P904FruitIntoBaskets {
    public static void main(String[] args) {
        Solution solution = new P904FruitIntoBaskets().new Solution();
        // TO TEST
    }


    class Solution {
        public int totalFruit(int[] fruits) {

            int n = fruits.length;
            Map<Integer, Integer> cnt = new HashMap<Integer, Integer>();
            int left = 0, ans = 0;
            for (int right = 0; right < n; ++right) {
                cnt.put(fruits[right], cnt.getOrDefault(fruits[right], 0) + 1);
                //循环删除，直到把数据删到只有一个
                while (cnt.size() > 2) {
                    cnt.put(fruits[left], cnt.get(fruits[left]) - 1);
                    if (cnt.get(fruits[left]) == 0) {
                        cnt.remove(fruits[left]);
                    }
                    ++left;
                }
                ans = Math.max(ans, right - left + 1);
            }
            return ans;
        }
    }
}
